public class Solution1 {
    //解法一 ： 归并排序，局部tmp[]

    public int[] sortArray(int[] nums) {
        mergeSort(nums, 0, nums.length - 1);
        return nums;
    }

    public void mergeSort(int[] nums, int left, int right) {
        if(left >= right) {
            return;
        }

        // 1. 根据中间点划分区间
        int mid = (left + right) / 2;
        // [left, mid] [mid + 1, right]

        // 2.先把左右两个区间排个序
        mergeSort(nums, left, mid);
        mergeSort(nums, mid + 1, right);

        // 3.合并两个有序数组
        int[] tmp = new int[right - left + 1];
        int cur1 = left;
        int cur2 = mid + 1;
        int i = 0;
        while(cur1 <= mid && cur2 <= right) {
            tmp[i++] = nums[cur1] <= nums[cur2] ? nums[cur1++] : nums[cur2++];
        }
        // 处理没有遍历的数组
        while(cur1 <= mid) {
            tmp[i++] = nums[cur1++];
        }
        while(cur2 <= right) {
            tmp[i++] = nums[cur2++];
        }

        // 4.还原
        for(int j = left; j <= right; j++) {
            nums[j] = tmp[j - left];
        }
    }

    //解法二 ： 归并排序，全局tmp[]
    int[] tmp;
    public int[] sortArray1(int[] nums) {
        tmp = new int[nums.length];
        mergeSort1(nums, 0, nums.length - 1);
        return nums;
    }

    public void mergeSort1(int[] nums, int left, int right) {
        if(left >= right) {
            return;
        }

        // 1. 根据中间点划分区间
        int mid = (left + right) / 2;
        // [left, mid] [mid + 1, right]

        // 2.先把左右两个区间排个序
        mergeSort1(nums, left, mid);
        mergeSort1(nums, mid + 1, right);

        // 3.合并两个有序数组
        int cur1 = left;
        int cur2 = mid + 1;
        int i = 0;
        while(cur1 <= mid && cur2 <= right) {
            tmp[i++] = nums[cur1] <= nums[cur2] ? nums[cur1++] : nums[cur2++];
        }
        // 处理没有遍历的数组
        while(cur1 <= mid) {
            tmp[i++] = nums[cur1++];
        }
        while(cur2 <= right) {
            tmp[i++] = nums[cur2++];
        }

        // 4.还原
        for(int j = left; j <= right; j++) {
            nums[j] = tmp[j - left];
        }
    }
}
